package com.wallace.downloadserver.typeHandler

import org.apache.ibatis.type.BaseTypeHandler
import org.apache.ibatis.type.JdbcType
import org.apache.ibatis.type.MappedJdbcTypes
import org.apache.ibatis.type.MappedTypes
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.sql.CallableStatement
import java.sql.PreparedStatement
import java.sql.ResultSet

/**
 * @Description:
 * List(Kotlin) 和 VARCHAR(JdbcType)的转换处理
 * @author Wallace
 * @Date 2022/1/28 15:26
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(List::class)
class ListHandler : BaseTypeHandler<List<String>>() {

    private val log: Logger = LoggerFactory.getLogger(javaClass)

    override fun setNonNullParameter(ps: PreparedStatement?, i: Int, parameter: List<String>?, jdbcType: JdbcType?) {
        val inputString = parameter?.joinToString(",")
        log.debug("inputString = $inputString")
        ps?.setString(i, inputString)
    }

    override fun getNullableResult(rs: ResultSet?, columnName: String?): List<String> {
        val outputString = rs?.getString(columnName)
        return outputString?.split(",") ?: listOf()
    }

    override fun getNullableResult(rs: ResultSet?, columnIndex: Int): List<String> {
        val outputString = rs?.getString(columnIndex)
        return outputString?.split(",") ?: listOf()
    }

    override fun getNullableResult(cs: CallableStatement?, columnIndex: Int): List<String> {
        val outputString = cs?.getString(columnIndex)
        return outputString?.split(",") ?: listOf()
    }
}